package c_leetcode.a_56_merge_intervals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

/**
 * 遍历 - 一层
 *
 * @author He Kuntao
 * @since 2025/3/14 15:44
 */
public class Foreach2 {
    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(new Foreach2().merge(new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}})));
    }

    public int[][] merge(int[][] intervals) {
        // 左端点排序
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));
        // 结果集
        ArrayList<int[]> result = new ArrayList<>();

        for (int[] interval : intervals) {
            int left = interval[0], right = interval[1];
            if (result.isEmpty() || left > result.get(result.size() - 1)[1]) {
                result.add(new int[]{left, right});
            } else {
                result.get(result.size() - 1)[1] = Math.max(result.get(result.size() - 1)[1], right);
            }
        }
        return result.toArray(new int[result.size()][]);
    }
}
